import { FC, useState, useEffect } from "react";
import { observer, inject } from "mobx-react";
import {
  Drawer,
  Button,
  Row,
  Col,
  Space,
  Tabs,
  List,
  Typography,
  Table,
  Tooltip,
} from "antd";
import { DownloadOutlined, PrinterOutlined } from "@ant-design/icons";

import { getReactorInfoList, transformArray } from "../../utils/index";
import math, { FIXEDINDEX } from "../../utils/math";
import {
  getDesignerReagent,
  getReactions,
  getDeskReagentConfig,
  createReactorExcelData,
} from "../../utils/exportDesigner";

import { ITStore } from "../../store";
import { ITDesinger } from "../../store/interfaces";

interface TProp {
  store: ITStore;
}

interface ITReactordrawer extends TProp {
  designerId: string;
}

interface ITDesingerInfo extends TProp {
  data: ITDesinger;
  treekeys: string[];
}

interface ITKeyIdx {
  key: string;
  idx: number;
}
const { Text } = Typography;

export const ReactionInfo: FC<ITDesingerInfo | any> = inject("store")(
  observer(({ store, data }: ITDesingerInfo) => {
    const {
      languageStore: { lang, langCur },
      designerStore: {
        getReactDesignerList,
        reactionDesignerList,
        createReactorExcel,
      },
      shelfStore: { allShelf },
      reagentStore: { getReagentInfoById, allReagent },
    } = store;

    const [currDesigner, setCurrDesigner] = useState<any>(null);
    const [loading, setLoading] = useState(false);

    const getData = async ({ id, userId }: any) => {
      await getReactDesignerList({
        designer: id,
        user: userId,
      });
    };

    useEffect(() => {
      if (data) {
        const { userInfo, id } = data;
        getData({ id, userId: userInfo.id });
      }
      setCurrDesigner(data);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data, lang]);

    const downReactionExcel = async (record: any) => {
      if (currDesigner && allShelf.length && allReagent.length) {
        setLoading(true);
        const { slotShelf, reactorSlotShelf, name } = currDesigner;
        const { reagentsort, slotreagent, plate } = record;

        let shelfName = slotShelf[plate].shelf;
        const shelfInfo = allShelf.find((item) => item.name === shelfName);
        const bottleList = shelfInfo?.bottleList || [];
        const bottleNames: string[] = [];
        if (bottleList.length > 0) {
          bottleList.forEach((item) => {
            bottleNames.push(item.name);
          });
        }
        const newbottleNames: any = transformArray(bottleNames);

        const { excelHeader, excelData } = createReactorExcelData({
          reagentsort,
          slotreagent,
          getReagentInfoById,
          plate,
          bottleNames: newbottleNames,
          shelfName
        });

        await createReactorExcel({
          name: `${name}_${record.name}`,
          excelHeader,
          excelData,
        });
        setLoading(false);
      }
    };

    const columns: any = [
      {
        title: lang["langreactionname"],
        dataIndex: "name",
        key: "name",
      },
      {
        title: lang["langreactionslotposition"],
        dataIndex: "plate",
        key: "plate",
      },
      {
        title: lang["langedit"],
        dataIndex: "reagent",
        key: "reagent",
        width: 100,
        align: "center",
        render: (text: string, record: any) => {
          return (
            <Tooltip title={lang["langdownloadreactionexcel"]} placement="topRight">
              <Button
                type="link"
                icon={<DownloadOutlined />}
                onClick={() => {
                  downReactionExcel(record);
                }}
              />
            </Tooltip>
          );
        },
      },
    ];

    return (
      <Table
        dataSource={reactionDesignerList}
        columns={columns}
        bordered
        loading={loading}
      />
    );
  })
);

const useReagents = ({ data, getReagentInfoById }: any) => {
  const [renderData, setRenderData] = useState<any[]>([]);

  useEffect(() => {
    let temp: any = [];
    if (data) {
      const { reagents } = data;
      if (reagents) {
        const slotReagents = { ...reagents };
        const slots = Object.keys(slotReagents);
        if (slots && slots.length) {
          slots.forEach((slotName: string) => {
            const bottleObj = slotReagents[slotName];
            const bottles = Object.keys(bottleObj);
            if (bottles && bottles.length) {
              bottles.forEach((bottleName: string) => {
                const reagentInfo = bottleObj[bottleName];
                const { reagentId, volume, weight, mmol, defaultAmount } =
                  reagentInfo;
                const reagent = getReagentInfoById(reagentId);
                if (reagent) {
                  let usedMmol = null;
                  let usedVolume = null;
                  let usedWeight = null;
                  if (
                    volume !== null &&
                    defaultAmount.volume !== null &&
                    defaultAmount.volume !== undefined
                  ) {
                    let temp: any = math.format(
                      math.evaluate(`${defaultAmount.volume} - ${volume}`),
                      FIXEDINDEX
                    );
                    usedVolume = temp - 0;
                  }
                  if (
                    weight !== null &&
                    defaultAmount.weight !== null &&
                    defaultAmount.weight !== undefined
                  ) {
                    let temp: any = math.format(
                      math.evaluate(`${defaultAmount.weight} - ${weight}`),
                      FIXEDINDEX
                    );
                    usedWeight = temp - 0;
                  }
                  if (
                    mmol !== null &&
                    defaultAmount.mmol !== null &&
                    defaultAmount.mmol !== undefined
                  ) {
                    let temp: any = math.format(
                      math.evaluate(`${defaultAmount.mmol} - ${mmol}`),
                      FIXEDINDEX
                    );
                    usedMmol = temp - 0;
                  }
                  // let tempUsed: any = math.format(math.evaluate(`${defaultAmount} - ${amount}`), FIXEDINDEX);
                  temp.push({
                    ...reagent,
                    defaultAmount,
                    key: slotName + bottleName,
                    slot: slotName,
                    position: bottleName,
                    used: {
                      mmol: usedMmol,
                      volume: usedVolume,
                      weight: usedWeight,
                    },
                  });
                }
              });
            }
          });
        }
      }
    }
    setRenderData(temp);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  return renderData;
};

export const ViewReagentList: FC<ITDesingerInfo | any> = inject("store")(
  observer(({ store, data, treekeys }: ITDesingerInfo) => {
    const {
      languageStore: { lang, langCur },
      reagentStore: { getReagentInfoById, getReagentUnit },
      dictionaryStore: { getDictValuesByKey },
    } = store;

    const [columns, setColumns] = useState<any>([]);

    const getShapeLabel = (value: string, _langCur: string) => {
      let label = "";
      getDictValuesByKey("reagentFormType").some((item) => {
        if (item.value === value) {
          label = item.label;
          if (_langCur === "zhcn") {
            label = item.cnlabel;
          }
          return true;
        }
        return false;
      });
      return label;
    };

    const tableData: any = useReagents({
      data,
      getReagentInfoById,
      getReagentUnit,
      lang,
    });

    useEffect(() => {
      const columnlist: any = [
        {
          title: lang["langname"],
          dataIndex: "name",
          key: "name",
        },
        {
          title: lang["langabbreviation"],
          dataIndex: "abbreviation",
          key: "abbreviation",
        },
        {
          title: lang["langcnname"],
          dataIndex: "cnname",
          key: "cnname",
        },

        {
          title: lang["langformula"],
          dataIndex: "formula",
          key: "formula",
        },
        {
          title: lang["langdensity"],
          dataIndex: "density",
          key: "density",
        },
        {
          title: lang["langpercentage"],
          dataIndex: "percentage",
          key: "percentage",
        },
        {
          title: lang["langmolecularweight"],
          dataIndex: "mw",
          key: "mw",
        },
        {
          title: lang["langmeltingpoint"],
          dataIndex: "mp",
          key: "mp",
        },
        {
          title: lang["langboilingpoint"],
          dataIndex: "bp",
          key: "bp",
        },
        {
          title: lang["langstructuralformula"],
          dataIndex: "structural",
          key: "structural",
          render: (url: string) => {
            if (url) {
              return <img src={url} width="60" alt="" />;
            }
            return null;
          },
        },
        {
          title: lang["langcasno"],
          dataIndex: "casno",
          key: "casno",
        },
        {
          title: lang["langslot"],
          dataIndex: "slot",
          key: "slot",
          align: "center",
        },
        {
          title: lang["langbottleposition"],
          dataIndex: "position",
          key: "position",
          align: "center",
        },
        {
          title: lang["langtype"],
          dataIndex: "type",
          key: "type",
          render: (text: string) => {
            return getShapeLabel(text, langCur);
          },
        },
        {
          title: lang["langvolatile"],
          dataIndex: "Volatile",
          key: "Volatile",
          align: "center",
          render: (text: string) => (text ? lang["langyes"] : lang["langno"]),
        },
        {
          title: lang["langviscose"],
          dataIndex: "Viscose",
          key: "Viscose",
          align: "center",
          render: (text: string) => (text ? lang["langyes"] : lang["langno"]),
        },
        {
          title: lang["langamount"],
          dataIndex: "defaultAmount",
          key: "defaultAmount",
          render: (def: any) => {
            let temp = [];
            if (def.mmol > 0) {
              temp.push(`${def.mmol}${lang["langmmol"]}`);
            }
            if (def.volume > 0) {
              temp.push(`${def.volume}${lang["langmlunit"]}`);
            }
            if (def.weight > 0) {
              temp.push(`${def.weight}${lang["langmg"]}`);
            }
            return temp.join(", ");
          },
        },
        {
          title: lang["langused"],
          dataIndex: "used",
          key: "used",
          render: (used: any) => {
            let temp = [];
            if (used.mmol > 0) {
              temp.push(`${used.mmol}${lang["langmmol"]}`);
            }
            if (used.volume > 0) {
              temp.push(`${used.volume}${lang["langmlunit"]}`);
            }
            if (used.weight > 0) {
              temp.push(`${used.weight}${lang["langmg"]}`);
            }
            return temp.join(", ");
          },
        },
        {
          title: lang["langnote"],
          dataIndex: "note",
          key: "note",
        },
      ];

      if (!treekeys || treekeys.indexOf("0") >= 0) {
        setColumns(columnlist);
      } else {
        const allkeys = [
          {
            key: "0-1",
            idx: 0,
          },
          {
            key: "0-2",
            idx: 1,
          },
          {
            key: "0-3",
            idx: 2,
          },
          {
            key: "0-4",
            idx: 3,
          },
          {
            key: "0-5",
            idx: 4,
          },
          {
            key: "0-6",
            idx: 5,
          },
          {
            key: "0-7",
            idx: 6,
          },
          {
            key: "0-8",
            idx: 7,
          },
          {
            key: "0-9",
            idx: 8,
          },
          {
            key: "0-10",
            idx: 9,
          },
          {
            key: "0-11",
            idx: 10,
          },
          {
            key: "0-12",
            idx: 11,
          },
          {
            key: "0-13",
            idx: 12,
          },
          {
            key: "0-14",
            idx: 13,
          },
          {
            key: "0-15",
            idx: 14,
          },
          {
            key: "0-16",
            idx: 15,
          },
          {
            key: "0-17",
            idx: 16,
          },
          {
            key: "0-18",
            idx: 17,
          },
          {
            key: "0-19",
            idx: 18,
          },
        ];
        let tempColumn: any = [];
        allkeys.forEach(({ key, idx }: ITKeyIdx) => {
          if (treekeys.indexOf(key) >= 0) {
            tempColumn.push(columnlist[idx]);
          }
        });
        setColumns(tempColumn);
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [treekeys, lang]);

    return (
      <Table
        dataSource={tableData}
        columns={columns}
        bordered
        size="small"
        scroll={{ x: 1200 }}
        pagination={false}
      />
    );
  })
);

const Reactordrawer: FC<ITReactordrawer | any> = ({
  store,
  designerId,
}: ITReactordrawer): JSX.Element => {
  const {
    languageStore: { lang, langCur },
    designerStore: {
      showDesingerDetail,
      changeShowDesingerDetail,
      getDesignerDetail,
      exportDesinger,
      createReactorExcel,
    },
    reagentStore: {
      getAllReagetList,
      allReagent,
      getReagentInfoById,
      getReagentUnit,
      getEnReagentUnit,
    },
    dictionaryStore: { getDictValuesByKey },
    workbenchStore: { getWorkbenchById },
    shelfStore: { getAllShelf, allShelf },
    bottleStore: { getAllBottle, allBottle },
    dictionaryStore: { fullDicts, getFullDict },
  } = store;

  const [designerData, setDesignerData] = useState<ITDesinger | null>(null);

  const [exportLoading, setExportLoading] = useState(false);

  useEffect(() => {
    if (!allReagent || !allReagent.length) {
      getAllReagetList();
    }
    if (!allBottle.length) {
      getAllBottle();
    }
    if (!allShelf.length) {
      getAllShelf();
    }
    if (!fullDicts || !fullDicts.length) {
      getFullDict(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    const getData = async () => {
      const result: ITDesinger | null = await getDesignerDetail({
        id: designerId,
      });
      setDesignerData(result);
    };

    if (designerId && showDesingerDetail) {
      getData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [designerId, showDesingerDetail]);

  const exportData = async () => {
    setExportLoading(true);

    const { name, workbench } = designerData || {};

    // 反应信息
    const reactionMessage = getReactorInfoList({
      lang,
      langCur,
      getReagentInfoById,
      getReagentUnit,
      designer: designerData,
    });

    const { designerReagentList, designerReagentTitle } = getDesignerReagent({
      lang,
      langCur,
      getReagentInfoById,
      getReagentUnit,
      designer: designerData,
      getDictValuesByKey,
    });

    const designerWorkbench: any = await getWorkbenchById({
      id: workbench,
    });

    const allShelf: any = await getAllShelf();
    const allBottle: any = await getAllBottle();

    const { deck_config, tuberackList } = getDeskReagentConfig({
      designer: designerData,
      designerWorkbench,
      allShelf,
      allBottle,
    });

    const exportDataObj = {
      id: designerId,
      name,
      txt: { reactionMessage },
      excel: { designerReagentList, designerReagentTitle },
      config: {
        reactions: getReactions({
          designer: designerData,
          getReagentInfoById,
          getEnReagentUnit,
          deck_config,
        }),
        deck_config,
      },
      tuberackList,
    };

    await exportDesinger(exportDataObj, () => {
      setExportLoading(false);
    });
  };

  const closeDrawer = () => {
    changeShowDesingerDetail(false);
  };

  const printClick = () => {
    window.open(`/print/${designerData?.id}`, "_blank");
  };

  return (
    <Drawer
      closable={false}
      onClose={closeDrawer}
      open={showDesingerDetail}
      destroyOnClose={true}
      width={"60%"}
      footer={
        <Row>
          <Col span={20}>
            <Space>
              <Tooltip title={lang["langdownloadreagentconf"]}>
                <Button
                  onClick={exportData}
                  type="primary"
                  icon={<DownloadOutlined />}
                  loading={exportLoading}
                >
                  {lang["langexport"]}
                </Button>
              </Tooltip>

              {/* <Button
                onClick={exportExcelData}
                type="primary"
                icon={<DownloadOutlined />}
                loading={exportLoading}
              >
                {lang["langreactionexcel"]}
              </Button> */}

              <Button onClick={printClick} icon={<PrinterOutlined />}>
                {lang["langprint"]}
              </Button>
            </Space>
          </Col>
          <Col span={4}>
            <Button onClick={closeDrawer} style={{ float: "right" }}>
              {lang["langclose"]}
            </Button>
          </Col>
        </Row>
      }
    >
      <Tabs
        defaultActiveKey={"1"}
        // onChange={tabChange}
        items={[
          {
            label: lang["langreactioninfo"],
            key: "1",
            children: <ReactionInfo data={designerData} />,
          },
          {
            label: lang["langreagentinfo"],
            key: "2",
            children: <ViewReagentList data={designerData} />,
          },
        ]}
      ></Tabs>
    </Drawer>
  );
};

export default inject("store")(observer(Reactordrawer));
